package com.zline.foodraise.listener;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.zline.foodraise.util.LUtil;

/**
 * Created by heshantao on 15/7/17.
 * RecyclerView 滑动监听
 */
public abstract class RecyclerOnScrollListener extends RecyclerView.OnScrollListener {
    private static final String LOG_TAG = RecyclerOnScrollListener.class.getSimpleName();
    LinearLayoutManager layoutManager;
    //RecyclerView 最后可见的item 位置
    int lastVisibleItemPosition = 0;
    //RecyclerView 可见的item个数
    int visibleItemCount = 0;
    //RecyclerView item的总数
    int totleItemCount = 0;
    //用来标记是否正在向最后一个滑动，既是否向右滑动或向下滑动
    boolean isSlidingToLast = false;

    public RecyclerOnScrollListener(LinearLayoutManager layoutManager) {
        this.layoutManager = layoutManager;
    }

    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
        if (newState == RecyclerView.SCROLL_STATE_IDLE) {//不滚动时
            visibleItemCount = layoutManager.getChildCount();
            totleItemCount = layoutManager.getItemCount();
            lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
            if (visibleItemCount > 0 && lastVisibleItemPosition >= totleItemCount - 1 && isSlidingToLast) {
                onLoadMore();
            }

        }
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        LUtil.i(LOG_TAG, "___________onScrolled_____________");
        if (dx > 0 || dy > 0) {
            //大于0表示，正在向右滚动
            isSlidingToLast = true;
        } else {
            //小于等于0 表示停止或向左滚动
            isSlidingToLast = false;
        }
    }

    //加载更多
    public abstract void onLoadMore();
}
